import interact from '../utils/interact'
import apiList from './apiList'
import Store from '../store'
import Vue from 'vue'
import qs from 'qs'

export default {
    request: options => {
        return new Promise((resolve, reject) => {
            const _options = Object.assign({
                method: "POST", // 请求方式
                url: "", // 请求地址
                data: {}, // 请求数据
                params: {}, // 请求参数
                header: {
                    'content-type': 'application/x-www-form-urlencoded'
                },
                requestType: 'uniRequest', //uniRequest, fetch
                resolveAllData: false,
                filterErrCode: '', //过滤掉一部分错误code不走默认的错误处理(String, Array, Number 都可以)
                noErrorToast: false,
                complete: null, // 请求结束后的回调函数（无论是否成功都会被调用）
                loadingIcon: true, // 是否显示loading状态动画
                relayLoading: false, //接力加载，只开始loading图标，但是不关闭
                timeout: 20000 // 超时时间。默认30000ms
            }, options);
            
            
            if(_options.url.indexOf('http') == -1) {
                _options.url = apiList.baseUrl + _options.url;
            }
            // 1秒钟内能返回的接口不弹出loading
            let loadingTimer;
            if (_options.loadingIcon) {
                loadingTimer = setTimeout(() => {
                    uni.showLoading({
                        title: "加载中",
                        icon: 'loading',
                        mask: true
                    });
                }, 200)
            }
            _options.data = _options.data || {}
            _options.data.platTypeNo = 'jdgzh'
            _options.data.platUniNo = 'jdpub'
            if(Store.state.user.account.token) {
                _options.data = {
                    token: Store.state.user.account.token,
                    ..._options.data
                }
            }

            for(let key in _options.data) {
                if(_options.data[key] === undefined) {
                    delete _options.data[key]
                }
            }
            

            let requestCon = {
                url: _options.url,
                method: _options.method || 'POST',

                data: _options.data,
                timeout: _options.timeout || 10000,
                complete: () => {
                    if (_options.loadingIcon && !_options.relayLoading) {
                        clearTimeout(loadingTimer)
                        uni.hideLoading();
                    }
                    typeof _options.complete === 'function' && _options.complete();
                },
                success: res => {
                    if (res.statusCode === 200) {
                        if (options.resolveAllData) {
                            return resolve(res.data)
                        }
                        const data = res.data
                        // data.date = res.header.date || res.header.Date
                        if (res.data.code === 1 ) {
                            resolve(data)
                        } else if(res.data.code == 10001) {
                            Store.commit('SET_ACCOUNT', {})
                            Store.commit('SET_USER_INFO', {})
                            interact.modal('登录失效，请重新登录').then(action => {
                                let searchQuery = qs.parse(location.search.slice(1))
                                delete searchQuery.token
                                let newSearchStr = qs.stringify(searchQuery)
                                if (process.env.NODE_ENV === 'development') { 
                                    uni.navigateTo({
                                        url: '/pages/login'
                                    });
                                } else {
                                    Vue.prototype.$toWxAuth(location.origin + location.pathname + (newSearchStr ? '?' + newSearchStr : ''))
                                    // if (navigator.userAgent.indexOf("MicroMessenger") > -1) {
                                    // } else {
                                    //     Vue.prototype.$toWxAuth(location.pathname + (newSearchStr ? '?' + newSearchStr : ''))
                                    // }
                                }
                            })
                        } else {
                            if(_options.filterErrCode != '') {
                                // 特定的code不弹出错误提示
                                if(typeof _options.filterErrCode == 'string' && res.data.code == _options.filterErrCode) {
                                } else if(typeof _options.filterErrCode === 'number' && res.data.code == _options.filterErrCode) {
                                } else if(_options.filterErrCode instanceof Array && _options.filterErrCode.indexOf(res.data.code) > -1) {
                                } else {
                                    interact.toast(res.data.msg)
                                }
                            } else {
                                if(!_options.noErrorToast) {
                                    interact.toast(res.data.msg)
                                }
                            }
                            // 添加错误信息，用于让异常捕获识别
                            res.data.name = "network request - " + _options.method;
                            res.data.api = _options.url;
                            res.data.apiParams = JSON.stringify(_options.data || {});
                            reject(res.data);
                        }
                    } else {
                        interact.toast({
                            400: '请求错误',
                            401: '未授权，请登录',
                            403: '拒绝访问',
                            404: '请求地址错误：' + options.url,
                            408: '请求超时',
                            500: '服务器内部错误',
                            501: '服务未实现',
                            502: '网关错误',
                            503: '服务不可用',
                            504: '网关超时',
                            505: 'HTTP版本不受支持'
                        }[res.statusCode] || "");
                    }
                },
                fail: err => {
                    console.error(err, _options.url);
                    interact.toast('网络错误，请重试');
                    reject(err);
                }
            }
            if (_options.header) {
                requestCon.header = _options.header
            }
            if(_options.requestType == 'fetch') {
                fetch(requestCon.url, {
                    method: requestCon.method,
                    headers: requestCon.header,
                    body: qs.stringify(requestCon.data),
                    keepalive: true, // 保持连接
                }).then(response => response.json())
                .then(res => {
                    requestCon.success({
                        errMsg: "request:ok",
                        statusCode: 200,
                        header: {},
                        data: res
                    })
                })
                .catch(error => console.error(error));
            } else {
                uni.request(requestCon)
            }
        })
    }
}
